<template>
  <div id="doctorConsultPlanPage">
    <!-- 工具欄 -->
    <a-space>
      <a-space>
        <a-button type="primary" @click="handleCreate">
          <template #icon>
            <PlusOutlined />
          </template>
          新建
        </a-button>
      </a-space>
    </a-space>
    <div class="data-box">
      <a-table
        :columns="columns"
        :data-source="tableData"
        :pagination="pagination"
        :loading="loading"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'consultPlanTitle'">
            <RouterLink
              :to="{
                name: 'ConsultPlanDetail',
                params: { id: record.consultPlanId },
              }"
            >
              {{ record.consultPlanTitle }}
            </RouterLink>
          </template>
          <template v-if="column.dataIndex === 'status'">
            <!-- 已過期：紅色（警告/失效） -->
            <a-tag color="red" v-if="record.endDate && record.endDate < nowDate"
              >已過期</a-tag
            >
            <!-- 未生效：灰色（未激活） -->
            <a-tag color="gray" v-else-if="record.startDate > nowDate"
              >待生效</a-tag
            >
            <!-- 生效中：綠色（成功/有效） -->
            <a-tag color="green" v-else>生效中</a-tag>
          </template>
          <template v-if="column.dataIndex === 'updatedAt'">
            {{ $formatDate(record.updatedAt) }}
          </template>
          <template v-if="column.key === 'action'">
            <a-button @click="handleEdit(record)">編輯</a-button>
            <a-button
              danger
              @click="handleDelete(record)"
              v-if="new Date(record.startDate) > new Date()"
              >刪除</a-button
            >
          </template>
        </template>
      </a-table>
    </div>
    <!-- 新建模態框 -->
    <a-modal
      v-model:open="showModalCreate"
      title="新建醫師診金分成方案"
      :footer="null"
    >
      <DynamicForm
        ref="createFormRef"
        :fieldConfig="createFieldConfig"
        @submit="handleCreateSubmit"
      />
    </a-modal>
    <!-- 修改模態框 -->
    <a-modal v-model:open="showModalEdit" :footer="null">
      <template #title>
        編輯醫師診金分成方案
        <a-tag color="warning"
          ><template #icon>
            <ExclamationCircleOutlined />
          </template>
          ID: {{ editFormData.id }}</a-tag
        >
      </template>
      <DynamicForm
        ref="editFormRef"
        :fieldConfig="editFieldConfig"
        @submit="handleEditSubmit"
        :formData="editFormData"
      />
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { message, Modal } from "ant-design-vue";
import { PlusOutlined, ExclamationCircleOutlined } from "@ant-design/icons-vue";
import DynamicForm from "@/components/DynamicForm.vue";
import {
  tableColumns,
  getCreteFieldConfig,
  getEditFieldConfig,
} from "@/models/doctorConsultPlan";
import { createPagination } from "@/utils/pagination";
import { doctorApi } from "@/api";
import { useRoute } from "vue-router";

//傳入的 props
const props = defineProps({
  doctorId: {
    type: Number,
    default: 0,
  },
});

const nowDate = new Date().toISOString().slice(0, 10);

const columns = tableColumns;
const createFieldConfig = ref<Record<string, any>>({});
const editFieldConfig = ref<Record<string, any>>({});
const route = useRoute();
const loading = ref(false);

const tableData = ref([]);
const editRecordId = ref<number>(0);
const editFormData = reactive<any>({});

onMounted(() => {
  fetchData();
});

const fetchData = async (params?: any) => {
  loading.value = true;
  try {
    const {
      data: { list, page, limit, total },
    } = await doctorApi.getDoctorConsultPlanList(props.doctorId, {
      ...params,
      pageSize: 5,
    });
    tableData.value = list || [];
    pagination.updatePagination(page, limit, total);
  } catch (error) {
    console.error("獲取醫師分成方案列表失敗", error);
  } finally {
    loading.value = false;
  }
};
const pagination = createPagination({ useRoute: false });

const handleTableChange = (pagination: {
  current: number;
  pageSize: number;
}) => {
  fetchData({
    page: pagination.current,
    page_size: pagination.pageSize,
  });
};

// 新建
const showModalCreate = ref(false);
const handleCreate = async () => {
  if (Object.keys(createFieldConfig.value).length === 0) {
    createFieldConfig.value = await getCreteFieldConfig();
  }
  showModalCreate.value = true;
};

const createFormRef = ref();
const handleCreateSubmit = async (data: any) => {
  try {
    const { validDate, ...rest } = data;
    const createData = {
      ...rest,
      startDate: validDate[0],
      endDate: validDate[1],
    };
    await doctorApi.createDoctorConsultPlan(props.doctorId, createData);
    message.success("創建分成方案成功");
    showModalCreate.value = false;
    createFormRef.value?.resetForm();
    fetchData(route.query);
  } catch (error) {
    console.error("創建醫師失敗:", error);
  } finally {
    createFormRef.value?.resetLoading();
  }
};

// 編輯

const showModalEdit = ref(false);
const handleEdit = async (record: any) => {
  if (Object.keys(editFieldConfig.value).length === 0) {
    editFieldConfig.value = await getEditFieldConfig();
  }
  editRecordId.value = Number(record.id);
  Object.assign(editFormData, {
    consultPlanId: Number(record.consultPlanId),
    validDate: [record.startDate, record.endDate],
  });
  console.log(editFormData);
  showModalEdit.value = true;
};

const editFormRef = ref();
const handleEditSubmit = async (data: any) => {
  try {
    const { validDate, ...rest } = data;
    const updateData = {
      ...rest,
      startDate: validDate[0],
      endDate: validDate[1],
    };
    await doctorApi.updateDoctorConsultPlan(
      props.doctorId,
      editRecordId.value,
      updateData
    );
    message.success("修改分成方案成功");
    showModalEdit.value = false;
    fetchData(route.query);
  } catch (error) {
    console.error("修改分成方案失敗", error);
  } finally {
    editFormRef.value?.resetLoading();
  }
};

// 刪除
const handleDelete = async (record: any) => {
  Modal.confirm({
    title: "確認刪除",
    content: `確定要刪除醫師診金分成方案 ${record.consultPlanTitle} 嗎？`,
    okText: "確定",
    cancelText: "取消",
    onOk: async () => {
      try {
        await doctorApi.deleteDoctorConsultPlan(props.doctorId, record.id);
        message.success("刪除醫師診金分成方案成功");
        fetchData();
      } catch (error) {
        console.error("刪除醫師診金分成方案失敗:", error);
      }
    },
  });
};
</script>

<style scoped></style>
